#include "baifa_cloud_client.h"
#include <QUrl>
#include <QUrlQuery>
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QDebug>

BaifaCloudClient::BaifaCloudClient(QObject *parent) : QObject(parent)
{
    m_manger = new QNetworkAccessManager(this);
    m_baseUrl = "https://apis.bemfa.com/va/";
    m_uid = "c661a39b03ea4872bb9010c100738f73"; // 设置默认私钥

    // 连接网络请求完成信号
    connect(m_manger, &QNetworkAccessManager::finished,
            this, &BaifaCloudClient::onReplyFinished);
}

void BaifaCloudClient::setUid(const QString &uid)
{
    m_uid = uid;
}

void BaifaCloudClient::getDeviceList()
{
    // 使用新的groupTopic API获取所有设备
    getDevicesByGroup();
}

void BaifaCloudClient::getAllGroups()
{
    if (m_uid.isEmpty()) {
        emit errorOccurred("未设置用户UID，请先调用setUid()");
        return;
    }

    QUrl url("http://apis.bemfa.com/vb/api/v1/allGroup");
    QUrlQuery query;
    query.addQueryItem("openID", m_uid);
    query.addQueryItem("type", "3"); // TCP协议设备
    url.setQuery(query);

    QNetworkRequest request(url);
    m_manger->get(request);
}
//实际上只了这个
void BaifaCloudClient::getDevicesByGroup(const QString &group)
{
    if (m_uid.isEmpty()) {
        emit errorOccurred("未设置用户UID，请先调用setUid()");
        return;
    }

    QUrl url("http://apis.bemfa.com/vb/api/v2/groupTopic");
    QUrlQuery query;
    query.addQueryItem("openID", m_uid);
    query.addQueryItem("type", "3"); // TCP协议设备
    if (!group.isEmpty()) {
        query.addQueryItem("group", group);
    }
    url.setQuery(query);

    QNetworkRequest request(url);
    m_manger->get(request);
}

void BaifaCloudClient::getDeviceInfo(const QString &topic)
{
    if (m_uid.isEmpty()) {
        emit errorOccurred("未设置用户UID，请先调用setUid()");
        return;
    }

    QUrl url(m_baseUrl + "getdeviceinfo");
    QUrlQuery query;
    query.addQueryItem("uid", m_uid);
    query.addQueryItem("topic", topic);
    url.setQuery(query);

    QNetworkRequest request(url);
    m_manger->get(request);
}

void BaifaCloudClient::getDeviceData(const QString &topic)
{
    if (m_uid.isEmpty()) {
        emit errorOccurred("未设置用户UID，请先调用setUid()");
        return;
    }

    QUrl url("http://apis.bemfa.com/va/getmsg");
    QUrlQuery query;
    query.addQueryItem("uid", m_uid);
    query.addQueryItem("topic", topic);
    query.addQueryItem("type", "3"); // TCP协议
    query.addQueryItem("num", "1"); // 获取最新1条数据
    url.setQuery(query);

    QNetworkRequest request(url);
    m_manger->get(request);
}

void BaifaCloudClient::onReplyFinished(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        emit errorOccurred("网络错误: " + reply->errorString());
        reply->deleteLater();
        return;
    }

    QByteArray data = reply->readAll();
    QString url = reply->url().toString();

    // 根据请求的URL判断是哪种类型的响应
    if (url.contains("getdevices")) {
        parseDeviceList(data);
    } else if (url.contains("getdeviceinfo")) {
        parseDeviceInfo(data);
    } else if (url.contains("getmsg")) {
        // 提取topic参数用于回调
        QUrlQuery query(reply->url());
        QString topic = query.queryItemValue("topic");
        parseDeviceData(data, topic);
    } else if (url.contains("allGroup")) {
        parseDeviceGroups(data);
    } else if (url.contains("groupTopic")) {
        parseDeviceList(data);
    }

    reply->deleteLater();
}

void BaifaCloudClient::parseDeviceList(const QByteArray &data)
{
    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (doc.isNull()) {
        emit errorOccurred("解析设备列表失败: 无效的JSON数据");
        return;
    }

    QJsonObject root = doc.object();
    if (root["code"].toInt() != 0) {
        emit errorOccurred("获取设备列表失败: " + root["msg"].toString());
        return;
    }

    // 处理新的API响应格式
    QJsonValue dataValue = root["data"];
    QJsonArray devices;
    
    if (dataValue.isArray()) {
        // 旧格式：data直接是数组
        devices = dataValue.toArray();
    } else if (dataValue.isObject()) {
        // 新格式：data是对象，设备列表在data.data中
        QJsonObject dataObj = dataValue.toObject();
        devices = dataObj["data"].toArray();
    }
    
    emit deviceListReceived(devices);
}

void BaifaCloudClient::parseDeviceInfo(const QByteArray &data)
{
    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (doc.isNull()) {
        emit errorOccurred("解析设备信息失败: 无效的JSON数据");
        return;
    }

    QJsonObject root = doc.object();
    if (root["code"].toInt() != 0) {
        emit errorOccurred("获取设备信息失败: " + root["msg"].toString());
        return;
    }

    QJsonObject deviceInfo = root["data"].toObject();
    emit deviceInfoReceived(deviceInfo);
}

void BaifaCloudClient::parseDeviceData(const QByteArray &data, const QString &topic)
{
    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (doc.isNull()) {
        emit errorOccurred("解析设备数据失败: 无效的JSON数据");
        return;
    }

    QJsonObject root = doc.object();
    if (root["code"].toInt() != 0) {
        emit errorOccurred("获取设备数据失败: " + root["msg"].toString());
        return;
    }

    QJsonArray dataArray = root["data"].toArray();
    if (!dataArray.isEmpty()) {
        QJsonObject deviceData = dataArray[0].toObject();
        emit deviceDataReceived(topic, deviceData);
    } else {
        emit errorOccurred("设备数据为空");
    }
}

void BaifaCloudClient::parseDeviceGroups(const QByteArray &data)
{
    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (doc.isNull()) {
        emit errorOccurred("解析设备分组失败: 无效的JSON数据");
        return;
    }

    QJsonObject root = doc.object();
    if (root["code"].toInt() != 0) {
        emit errorOccurred("获取设备分组失败: " + root["msg"].toString());
        return;
    }

    QJsonObject dataObj = root["data"].toObject();
    QJsonArray groups = dataObj["data"].toArray();
    emit deviceGroupsReceived(groups);
}
